import os
import os.path
from string import split
import logging
from pylons import config

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from authkit.authorize.pylons_adaptors import authorized
from authkit.permissions import HasAuthKitRole, ValidAuthKitUser, And

from arkaiv.lib.base import BaseController, render, model
from arkaiv.model.oggzinfo import OggzInfo
from arkaiv.model.cmmlparser import cmmlParser
from arkaiv.model.framer import Frame
from arkaiv.model.imager import Imager

log = logging.getLogger(__name__)

path_base = config['media_path_base']
media_url_base = config['media_url_base']

class ItemController(BaseController):

    def index(self):
        # Return a rendered template
        #return render('/item.mako')
        # or, return a response
        return 'Hello World'

    def displayitem(self):

        itemid = request.params['id']
        toedit = request.params['edit']
        try:
            c.playclip = request.params['playclip']
            #print c.playclip
        except:
            c.playclip = ""


        c.itemid = itemid
        c.itemname = model.getitemname(itemid)
        cmmlfile = model.getitemcmmlfile(itemid)
        # get clip information
        c.cliplist = model.getclipinfoforitem(itemid) 
        # get the head information now
        c.headdict = model.getheadinfoforitem(itemid) 
        # And now meta info - a list of dicts

        # FIXME - this should be just a list of the meta objects - why return a
        # dict?

        c.metalist = model.getmetainfoforhead(c.headdict['index'])
        c.source = model.getsourcesforitem(itemid)
        sourcedict = {}
        oggsource = model.getsourcepath(c.source)

        # convert path to a useful url for the web server
        urlpath = split(cmmlfile, path_base)
        # Now split off the extension
        urlpath = os.path.splitext(urlpath[1])[0]
        clipimageurl = media_url_base + os.path.dirname(urlpath) + "/"
        #url = media_url_base + urlpath + ".anx"
        url = media_url_base + urlpath + ".ogg"
        if c.playclip=="":
            sourcedict['clipdetail'] = ""
        else:
            sourcedict['clipdetail'] = "?id=" + c.playclip

        sourcedict['urlpath'] = url   # + "?id=" + c.playclip
        sourcedict['clipimageurl'] = clipimageurl
        # now get some source info:
        o = OggzInfo(oggsource)
       	sourcedict['duration'] = o.duration()
       	sourcedict['bitrate'] = o.bitrate()
       	sourcedict['resolution'] = o.resolution()
       	sourcedict['framerate'] = o.framerate()
       	sourcedict['audio'] = o.audio()
        if (o.has_video()):
            sourcedict['has_video'] = "Yes"
        else:
            sourcedict['has_video'] = "No"
            
        if (o.has_audio()):
            sourcedict['has_audio'] = "Yes"
        else:
            sourcedict['has_audio'] = "No" 
        c.sourcedict = sourcedict
        
        if authorized(HasAuthKitRole('admin')):
            return render('/displayitemadmin.mak')
        else:
            return render('/displayitem.mak')

    def addmetainfo(self):
        metadict = {}
        metadict['headindex'] = request.params['headindex']
        metadict['itemid'] = request.params['itemid']
        metadict['id'] = request.params['metaid']
        metadict['name'] = request.params['metaname']
        metadict['content'] = request.params['metacontent']
        metadict['scheme'] = request.params['metascheme']
        # pass a dict in to the model
        metaid = model.addmeta(metadict)

        model.syncmetaid(metaid)
        cmmlfile = model.getitemcmmlfile(metadict['itemid'])
        parser = cmmlParser()
        parser.setcmmlfilename(cmmlfile)
        parser.addmetaitem(metadict)
        # add this to the cmml file
        redirect_to(action='displayitem', id=metadict['itemid'], edit="yes")


    def deletemeta(self):
        """ Deletes a meta tag for an item
        """
        metaid = request.params['metaid']
        itemid = request.params['itemid']
        headid = request.params['headid']
        print "itemid is" + str(itemid)
        model.deletemeta(metaid)
        # easier to read meta info and add all in one go?
        metalist = model.getmetasforhead(headid)
        print metalist
        # now write these back to the cmml file
#        parser = ...
        cmmlfile = model.getitemcmmlfile(itemid)
        parser = cmmlParser()
        parser.setcmmlfilename(cmmlfile)
        parser.syncheadmetas(metalist)

        redirect_to(action='displayitem', id=itemid, edit="yes")

    def addclip(self):
        clip = {}
        if request.params['starttime'] == "":
            clip['starttime'] = 0
        else: 
            clip['starttime'] = float(request.params['starttime'])
        if (not request.params['endtime']):
            print "no value for endtime"
            clip['endtime'] = ""
        else:
            clip['endtime'] = float(request.params['endtime'])
        clip['itemid'] = request.params['itemid']
        clip['a_text'] = request.params['a_text']
        clip['id'] = clip['starttime'] # A kludge so users don't have to worry about providing ids
        clip['a_href'] = request.params['a_href']
        clip['desc'] = request.params['desc']
        has_video = request.params['hasvideo']

        # first get the source file info
        cmmlfile = model.getitemcmmlfile(clip['itemid'])

        # create an image to display for the clip
        if has_video == "Yes":
            clipimage = Imager()
            clip['img_src'] = clipimage.createimageforclip(cmmlfile, clip)

        else:
            clip['img_src'] = ""

        model.addclip(clip)
        # Now the same information added to the cmml file
        # Clips need to be in temporal order so redo the whole lot
        # Get a list of clip dictionary objects
        cliplist = model.getclipinfoforitem(clip['itemid'])
        parser = cmmlParser()
        parser.setcmmlfilename(cmmlfile)
        parser.addclipstocmmlfile(cliplist)
        redirect_to(action='displayitem', id=clip['itemid'], 
                    playclip=clip['id'], edit="yes")

    def deleteclip(self):
        clipid = request.params['clipid']
        itemid = request.params['itemid']
        model.deleteclip(clipid)
        # Now update the cmml file
        cmmlfile = model.getitemcmmlfile(itemid)
        cliplist = model.getclipinfoforitem(itemid)
        parser = cmmlParser()
        parser.setcmmlfilename(cmmlfile)
        parser.addclipstocmmlfile(cliplist)

        redirect_to(action='displayitem', id=itemid, edit="yes")

    def deleteitem(self):
        itemid = request.params['itemid']
        model.deleteitem(itemid)

        # FIXME - the source files aren't actually removed from the
        # application's media directory by doing this - at this stage I regard
        # this as a feature...

        redirect_to(controller='list', action='index')

    def edititemname(self):
        """ Called from the Ajax in place editor

            returns the item name
        """
        text = request.params['myparam']
        itemid = request.params['itemid']

        # change this element in the database
        model.edititemname(itemid, text)

        #  Item title is not in the cmml file - although I guess it could be
        #  linked?  On import, the item title is the same as the head title
        
        return text

    def editheadinfo(self):
        headinfo = {}
        headinfo['itemid'] = request.params['itemid']
        headinfo['id'] = request.params['headid']
        headinfo['title'] = request.params['headtitle']
        model.edithead(headinfo)

        parser = cmmlParser()
        cmmlfilename = model.getitemcmmlfile(headinfo['itemid'])
        parser.setcmmlfilename(cmmlfilename)
        parser.edithead(headinfo['id'], headinfo['title'])
        # Assume that if we get here we have the OK to edit...
        redirect_to(action='displayitem', id=headinfo['itemid'], edit="yes")


    def editheadmetaname(self):
        text = request.params['myparam']
        id = request.params['id']
        itemid = request.params['itemid']
        field = request.params['field']

        # change this element in the database
        model.editmeta(id, field, text)
        # change this element in the cmml file
        parser = cmmlParser()
        cmmlfilename = model.getitemcmmlfile(itemid)
        parser.setcmmlfilename(cmmlfilename)
        parser.editmeta(id, field, text)
        
        return text


